<?php

namespace app\common\model\shop;

use app\admin\library\Auth;
use app\common\library\Auth as LibraryAuth;
use app\common\model\Acct;
use app\common\model\Achdiscount;
use app\common\model\Admin;
use app\common\model\shop\goods\Acct as GoodsAcct;
use app\common\model\shop\goods\User;
use Hyc;
use Jdy;
use think\Cache;
use think\Model;
use traits\model\SoftDelete;

class Goods extends Model
{

    use SoftDelete;



    // 表名
    protected $name = 'shop_goods';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'sale_switch_text',
        'thumb_image_str',
        'images_array',
        'user_json',
        'acct_json',
        'check_image_str',
        'acct_str',
        'goods_acct',
    ];
    public function getAcctStrAttr($value, $data)
    {
        if (isset($data['acct_ids'])) {
            $admin_id = Acct::whereIn('id', $data['acct_ids'])->column('admin_id');
            return implode(',', Admin::whereIn('id', $admin_id)->column('nickname'));
        }
    }
    public function getImagesArrayAttr($value, $data)
    {
        if (isset($data['images']) && $data['images']) {
            $arr = explode(',', $data['images']);
            foreach ($arr as &$v) {
                $v = cdnurl($v, true);
            }
            return $arr;
        }
        return [];
    }
    public function getUserJsonAttr($value, $data)
    {
        return json_encode(User::all(['goods_id' => $data['id']]));
    }
    public function getAcctJsonAttr($value, $data)
    {
        return json_encode(GoodsAcct::all(['goods_id' => $data['id']]));
    }
    public function getThumbImageStrAttr($value, $data)
    {
        return isset($data['thumb_image']) && $data['thumb_image'] ? cdnurl($data['thumb_image'], true) : '';
    }
    public function getCheckImageStrAttr($value, $data)
    {
        return isset($data['check_image']) && $data['check_image'] ? cdnurl($data['check_image'], true) : '';
    }

    // function getPriceAttr($value, $data)
    // {
        // $price = $data['price'] ?? 0;
        // $auth = LibraryAuth::instance();

        // if ($auth->isLogin()) {
        //     $acct_id = $auth->acct_id;
        // } else {
        //     $auth = Auth::instance();
        //     $acct_id = $auth->acct_id ?? 50;
        // }
        // if ($acct_id) {
        //     $price = GoodsAcct::where('acct_id', $acct_id)->where('goods_id', $data['id'])->value('price') ?? $price;
            // $cache_id = 'acct_discount:' . $acct_id;
            // $discount = Cache::get($cache_id);
            // if ($discount) {
            //     $price = bcmul($price, $discount / 100, 2);
            // } else {
            //     $acct = Acct::where('id', $acct_id)->find();
            //     $discount = Achdiscount::where('money', '<=', $acct->lastmonth_ach)->order('money desc')->limit(1)->select();
            //     if (count($discount)) {
            //         $discount = $discount[0];
            //         Cache::set($cache_id, $discount['discount']);
            //         $price = bcmul($price, $discount['discount'] / 100, 2);
            //     }
            // }
        // }
        // return $price;
    // }


    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
            // if (!$row->product_code) {
            // $api = new Hyc();
            // $api->addGoods($row);
            // $row->save();
            // }
            if ((!isset($row->jdy_id) || !$row->jdy_id)) {
                // $api = new Jdy(['acct_id' => 50]);
                // $api->addGoods($row);
                // $row->save();
            }
            
        });


        self::afterUpdate(function ($row) {
            $original = $row->origin;
            $change = $row->getChangedData();
            if (isset($change['stock']) && $change['stock'] != $original['stock']) {

                $auth = new Auth();
                $admin_id = $auth->isLogin() ? $auth->id : 0;
                $log = new \app\common\model\shop\Goodsstocklog();
                // $log->acct_id = $row->acct_id;
                $log->goods_id = $row->id;
                $log->admin_id = $admin_id;
                $log->before = $original['stock'];
                $log->after = $change['stock'];
                $log->save();
            }
        });
    }


    public function getSaleSwitchList()
    {
        return ['1' => __('Sale_switch 1'), '0' => __('Sale_switch 0')];
    }


    public function getSaleSwitchTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['sale_switch']) ? $data['sale_switch'] : '');
        $list = $this->getSaleSwitchList();
        return isset($list[$value]) ? $list[$value] : '';
    }



    public function getGoodsAcctAttr($v, $data)
    {
        $auth = LibraryAuth::instance();
        if ($auth->isLogin() && $auth->acct_id) {
            $goods = GoodsAcct::where('acct_id', $auth->acct_id)->where('goods_id', $data['id'])->find();
            if (!$goods) {
                return [];
            }
            $purchase_price = $goods['purchase_price'] ?? 0;

            $acct_id = $auth->acct_id;
            $cache_id = 'acct_discount:' . $acct_id;
            $discount = Cache::get($cache_id);
            if ($discount) {
                $purchase_price = bcmul($purchase_price, $discount / 100, 2);
            } else {
                $acct = Acct::where('id', $acct_id)->find();
                $discount = Achdiscount::where('money', '<=', $acct->lastmonth_ach)->order('money desc')->limit(1)->select();
                if (count($discount)) {
                    $discount = $discount[0];
                    Cache::set($cache_id, $discount['discount']);
                    $purchase_price = bcmul($purchase_price, $discount['discount'] / 100, 2);
                }
            }

            $goods->purchase_price = $purchase_price;

            return  $goods;
        }
        return [];
    }

    public function category()
    {
        return $this->belongsTo('app\common\model\Category', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function first()
    {
        return $this->belongsTo('app\common\model\Category', 'first_cate', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
